import React, { Component } from "react";
import { connect } from "dva";
import Drawer from "react-motion-drawer";
import { Form, Input, Button, TreeSelect, notification } from "antd";

import PartmentButton from "../../../components/PartmentButton";

import "./less/depart.less";
import {
  systemComDepartGet, //通过ID获取部门功能
  systemComDepartUpdate //部门更新--编辑保存
} from "../../../services/api";

const FormItem = Form.Item;
const style = {
  background: "#F9F9F9",
  boxShadow: "0 2px 11px 0 rgba(15, 113, 255, 0.2)"
};
const drawerProps = {
  overlayColor: "rgba(0,0,0,0)",
  drawerStyle: style
};
// const { MenuItemGroup } = Menu;

@connect(state => ({
  profile: state.profile
}))
@Form.create()

/**
 * 部门管理组件
 */
export default class EditDepartment extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      open: this.props.open,
      departName: "", //部门名称
      departId: "", //部门Id
      perID: "", //新人员ID
      oldPerID: "", //原部门主管人员ID
      parentDepartId: "", //上级部门ID
      DepartTree: this.props.treeData || [], //部门树
      checkedkeys: "",
      addDepartmentUserVisible: false
    };
  }
  componentDidMount() {}
  componentWillReceiveProps(nextProps) {
    //console.log(nextProps, this.state, "componentWillReceiveProps-nextProps");

    if (
      JSON.stringify(this.state.DepartTree) !==
      JSON.stringify(nextProps.treeData)
    ) {
      this.setState({ DepartTree: nextProps.treeData });
    }
    if (nextProps.open !== this.state.open) {
      this.setState({ open: nextProps.open });
    }

    if (nextProps.departId !== this.state.departId) {
      if (nextProps.departId === "-1" || nextProps.departId === undefined) {
        return;
      }
      this.setState({ departId: nextProps.departId });
      this.systemComDepartGet(nextProps.departId);
    }
  }
  //部门更新--编辑保存
  systemComDepartUpdate = values => {
    systemComDepartUpdate({
      departName: values.departName, //部门名称
      departId: this.state.departId, //部门Id
      perID: values.perID ? this.state.perID : "",
      oldPerID: this.state.oldPerID, //原部门主管人员ID
      parentDepartId: values.parentDepartId //上级部门ID
    }).then(
      response => {
        console.log(
          response,
          "systemComDepartUpdate--response-部门更新--编辑保存"
        );
        this.props.editSuccess();
        this.setState({ open: false, departId: "" });
      },
      err => {
        console.log(err, "systemComDepartUpdate-err-部门更新--编辑保存");
      }
    );
  };

  // 通过ID获取部门功能
  systemComDepartGet = departId => {
    systemComDepartGet({ departId }).then(
      response => {
        console.log(
          response,
          "systemComDepartGet--response- 通过ID获取部门功能"
        );
        const { data } = response;
        const { setFieldsValue } = this.props.form;
        setFieldsValue({
          parentDepartId: data.parentDepartId || "",
          departName: data.departName || "",
          perID: data.oldPerName
        });
        this.setState({
          departName: data.departName || "", //部门名称
          departId: data.departId || "", //部门Id
          perID: data.oldPerID || "", //新人员ID
          oldPerID: data.oldPerID || "", //原部门主管人员ID
          checkedkeys: data.oldPerID || "", //原部门主管人员ID
          parentDepartId: data.parentDepartId || "" //上级部门ID
        });
      },
      err => {
        console.log(err, "systemComDepartGet-err- 通过ID获取部门功能");
      }
    );
  };

  //保存编辑部门表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values, "handleSubmit-values");
      if (!err) {
        this.systemComDepartUpdate(values);
        console.log("Received values of form: ", values);
      }
    });
  };

  render() {
    const { getFieldDecorator, setFieldsValue } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 }
      }
    };
    return (
      <Drawer
        {...drawerProps}
        right
        open={this.state.open}
        noTouchClose
        width={594}
        zIndex={2}
        onChange={open => {
          this.setState({ open });
          this.props.ok(open);
        }}
      >
        <div
          style={{
            backgroundColor: "#fff",
            width: "100%",
            height: "100%"
          }}
          className="edit-department"
        >
          <header className="edit-header">
            <h2>编缉部门</h2>
          </header>
          <div className="edit-form">
            <Form
              onSubmit={this.handleSubmit}
              style={{ marginTop: 24 }}
              className="edit-form"
            >
              <FormItem {...formItemLayout} label="部门名称">
                {getFieldDecorator("departName", {
                  initialValue: this.state.departName,
                  rules: [
                    {
                      required: true,
                      message: "请输入"
                    },
                    {
                      pattern: /[\u4e00-\u9fa5]/,
                      message: "请输入汉字"
                    }
                  ]
                })(<Input placeholder="请输入" maxLength="20" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="上级部门">
                {getFieldDecorator("parentDepartId", {
                  initialValue: this.state.parentDepartId,
                  rules: [
                    {
                      required: true,
                      message: "请选择"
                    }
                  ]
                })(
                  <TreeSelect
                    dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                    treeData={this.state.DepartTree}
                    placeholder="请选择上级部门"
                    treeDefaultExpandAll
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="设置主管">
                {getFieldDecorator("perID", {
                  initialValue: ""
                })(
                  <Input
                    onClick={() => {
                      this.setState({ addDepartmentUserVisible: true });
                    }}
                    placeholder="请选择"
                  />
                )}
              </FormItem>
              {/* 设置主管人员选择 */}
              <PartmentButton
                handleCancel={() => {
                  this.setState({ addDepartmentUserVisible: false });
                }}
                onCheck={(checkedkeys, selectUser) => {
                  console.log(
                    checkedkeys,
                    selectUser,
                    "checkedkeys-selectUser"
                  );
                  const user = selectUser[0];
                  this.setState({
                    perID: selectUser.length > 0 ? user.key : "",
                    addDepartmentUserVisible: false,
                    checkedkeys
                  });
                  setFieldsValue({
                    perID: selectUser.length > 0 ? user.title : ""
                  });
                }}
                value={this.state.checkedkeys}
                visible={this.state.addDepartmentUserVisible}
                type="radio"
              />
              <div className="edit-option">
                <Button
                  onClick={() => {
                    this.props.ok(false);
                    this.setState({ open: false, departId: "" });
                  }}
                >
                  取消
                </Button>
                <Button
                  style={{ marginLeft: 8 }}
                  type="danger"
                  onClick={() => this.props.delete()}
                >
                  删除
                </Button>
                <Button
                  style={{ marginLeft: 8 }}
                  type="primary"
                  htmlType="submit"
                >
                  保存
                </Button>
              </div>
            </Form>
          </div>
        </div>
      </Drawer>
    );
  }
}
